package cn.stronglink.assetmanage.business.repair.order;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.repair.assetlist.RepairDetailListActivity;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.SyncTypesDao;
import cn.stronglink.assetmanage.entity.MessageEvent;
import cn.stronglink.assetmanage.entity.RepailDetail;
import cn.stronglink.assetmanage.entity.Repair;
import cn.stronglink.assetmanage.entity.Result;
import cn.stronglink.assetmanage.entity.SyncTypes;
import cn.stronglink.assetmanage.entity.User;
import cn.stronglink.assetmanage.listener.onRecyclerListener;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.assetmanage.utils.dao.RepairDataUtil;
import cn.stronglink.netrequest.business.repail.RepairService;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 未入库表单列表
 * A simple {@link Fragment} subclass.
 */
public class UnRepairFragment extends Fragment implements onRecyclerListener {

    private Unbinder mUnbinder;
    @BindView(R.id.rv_uncheck)
    RecyclerView rvUnCheck;
    @BindView(R.id.sfl_uncheck_order)
    SwipeRefreshLayout sflUncheckOrder;
    private RepaierOrderAdapter mRepaierAdapter;
    private List<Repair> unRepaierList;
    private RepairService mRepaierService;
    private Map<String, Repair> repairMap = new HashMap<>();    //获取数据库的维修单列表

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_un_check, container, false);
        mUnbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initViewAndData();
    }

    private void initViewAndData() {
        mRepaierAdapter = new RepaierOrderAdapter(getActivity());
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayout.VERTICAL,
                false);
        rvUnCheck.setLayoutManager(layoutManager);
        rvUnCheck.setAdapter(mRepaierAdapter);
        mRepaierAdapter.setListener(this);
        sflUncheckOrder.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshUncheckData();
            }
        });
        mRepaierService = new RepairService();
        //显示本地数据
        showUnRepaierData();
    }


    private void showUnRepaierData() {
        unRepaierList = RepairDataUtil.getDataByunRepairDistince();
        if (mRepaierAdapter != null) {
            mRepaierAdapter.notifyDataChanged(unRepaierList);
        }

    }

    /**
     * 刷新未入库数据
     */
    private void refreshUncheckData() {
        //判断是离线还是在线
        SyncTypes syncTypes = DaoManager.getDaoSession(this.getActivity()).getSyncTypesDao().
                queryBuilder().where(SyncTypesDao.Properties.IsSelected.eq(true)).unique();
        int tp = 0;
        if (syncTypes != null) {
            tp = syncTypes.getSyscTs();
        }
        switch (tp) {
            case Constants.STATUS_ONE:
                //自动
                getCheckData();
                break;
            case Constants.STATUS_TWO:
                //离线，从数据库拿数据
                stopRefresh();
                ToastUtil.toastShort("本地数据加载完成");
                break;
            default:
                break;
        }
    }

    private void stopRefresh() {
        if (sflUncheckOrder != null) {
            sflUncheckOrder.setRefreshing(false);
        }
    }

    private void getCheckData() {
        if (mRepaierService != null) {
            try {
                mRepaierService.downloadRepairWorkOrder(User.getInstance().getId_(), new Callback() {
                    @Override
                    public void onFailure(Call call, final IOException e) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                stopRefresh();
                                ToastUtil.toastShort(e.getMessage());
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, final Response response) throws IOException {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                stopRefresh();
                            }
                        });
                        saveRepaierData(response);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void saveRepaierData(final Response response) {
        try {
            if (response.isSuccessful()) {
                if (response.code() == 200) {
                    String json = response.body().string();
                    if (json != null && !"".equals(json)) {
                        Result<List<Repair>> repairResult = null;
                        Gson gson = new Gson();
                        repairResult = gson.fromJson(json, new TypeToken<Result<List<Repair>>>() {
                        }.getType());
                        if (repairResult != null && repairResult.getHttpCode() == HttpURLConnection.HTTP_OK) {
                            if (repairResult.getData() != null) {
                                List<Repair> repairList = repairResult.getData();
                                // 验收单列表
                                if (repairList != null && repairList.size() > 0) {
                                    List<Repair> repairMod = RepairDataUtil.getDataByRepairIdDistince();
                                    for (Repair repair : repairMod) {
                                        repairMap.put(repair.getId_(), repair);
                                    }
                                    for (Repair repair : repairList) {
                                        if (!repairMap.containsKey(repair.getId_())) {
                                            repairMap.put(repair.getId_(), repair);
                                            DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getRepairDao().insertOrReplace(repair);
                                            // 获取详情
                                            if (repair.getDetailList() != null && repair.getDetailList().size() > 0) {
                                                for (RepailDetail repailDetail : repair.getDetailList()) {
                                                    repailDetail.setRepairId_(repair.getId_());
                                                    DaoManager.getDaoSession(MyApplication.APP_CONTEXT).getRepailDetailDao().insertOrReplace(repailDetail);
                                                }
                                            }
                                        }
                                    }
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            ToastUtil.toastShort("下载维修单成功");
                                            //通知Activity更新数据
                                            MessageEvent messageEvent = new MessageEvent();
                                            messageEvent.setType(Constants.UPDATE_REPAIR_DATA);
                                            EventBus.getDefault().post(messageEvent);
                                        }
                                    });
                                } else {
                                    ToastUtil.toastShort(MyApplication.APP_CONTEXT.getString(R.string.get_no_data));
                                }
                            } else {
                                ToastUtil.toastShort(MyApplication.APP_CONTEXT.getString(R.string.get_no_data));
                            }
                        } else {
                            ToastUtil.toastShort(MyApplication.APP_CONTEXT.getString(R.string.get_no_data));
                        }
                    } else {
                        ToastUtil.toastShort(MyApplication.APP_CONTEXT.getString(R.string.get_no_data));
                    }
                } else {
                    ToastUtil.toastShort(response.message());

                }
            } else {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.toastShort(MyApplication.APP_CONTEXT.getString(R.string.get_data_fail));
                    }
                });
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mUnbinder.unbind();
    }

    @Override
    public void onItemClicked(View v, int postion) {
        Intent intent = new Intent(getActivity(), RepairDetailListActivity.class);
        intent.putExtra(Constants.SEARCH_REPAIR_NO, unRepaierList.get(postion).getId_());
        startActivity(intent);
    }
}
